package stardust.product.xspider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.script.ScriptException;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import stardust.core.log.Log;
import stardust.core.network.protocol.http.HttpRequestMeta;
import stardust.core.network.protocol.http.HttpResponseMeta;
import stardust.core.support.db.DataAccessObject;
import stardust.core.support.db.StardustDB;
import stardust.core.support.js.JavaScriptExecuteor;

public class YMXK_Main
{
  
  public static final Log log = new Log(YMXK_Main.class);
  
  public static String toArrayString(List<String> list)
  {
    StringBuffer buff = new StringBuffer();
    
    for (int i = 0; i < list.size(); i++)
    {
      buff.append(list.get(i)).append(i < list.size() - 1 ? ", " : "");
    }
    
    return buff.toString();
  }

  public static void main(String[] args) throws InterruptedException, ScriptException
  {
    final JavaScriptExecuteor js = new JavaScriptExecuteor("function getBD(script) {eval(script); return BdPlayer['url'];}");
    
    XSpider s = new XSpider(new AbstractXSpiderCallback("www.yetwo.com:80", "yetwo.com")
    {
      public void resolve(XSpiderURL url, HttpRequestMeta reqMeta, HttpResponseMeta rspMeta, String encode, String title, String html)
      {
        super.resolve(url, reqMeta, rspMeta, encode, title, html);
        
        /*
         * 分析页面内容。
         */
        if (html != null)
        {
          Parser parser;
          NodeList nl;
          
          try
          {
            parser = Parser.createParser(html, encode);
            boolean isPlayPage = (nl = parser.parse(new HasAttributeFilter("id", "GxPlayer"))).size() > 0;
            parser.reset();
            boolean isInfoPage = !isPlayPage &&(nl = parser.parse(new HasAttributeFilter("class", "o_r_contact"))).size() > 0;
            
            /*
             * 播放页面。
             */
            if (isPlayPage)
            {
              //Node scriptNode = nl.elementAt(0).getChildren().elementAt(1);
              parser.reset();
              nl = parser.parse(new HasAttributeFilter("id", "GxPlayer"));
              Node scriptNode = nl.elementAt(0).getChildren().elementAt(1).getFirstChild();
              String script = null;
              if (scriptNode != null)
              {
                script = scriptNode.getText();
                
                try
                {
                  script = (String) js.execute("getBD", script);
                }
                catch (Exception e)
                {
                  e.printStackTrace();
                }
              }
              
              // 解析当前视频信息
              parser.reset();
              nl = parser.parse(new HasAttributeFilter("class", "kp_flash_title"));
              String moiveInfoName = null;
              String moiveInfo = null;
              // <div class="kp_flash_title"><h1>正在播放：<a href="/juqing/31242/" target="_blank">刺杀林肯</a> HD</h1><script type="text/javascript" src="/temp/Banner/play-jia.js" charset="utf-8"></script></div>
              
              if (nl.size() > 0)
              {
                moiveInfoName = nl.elementAt(0).getFirstChild().getChildren().elementAt(1).getFirstChild().getText();
                moiveInfo = nl.elementAt(0).getFirstChild().getChildren().elementAt(2).getText();
              }
              
              DataAccessObject dao = StardustDB.getDataAccessObject();
              
              try
              {
                Map<String, Object> m = dao.get("SELECT MOIVE_ID FROM TB_SD_MOIVE WHERE MOIVE_NAME = ?", moiveInfoName);
                
                if (m != null)
                {
                  Integer moiveId = Integer.parseInt(m.get("MOIVE_ID").toString());
                  dao.execute("INSERT INTO TB_SD_MOIVE_FILE VALUES (NULL, NOW(), NULL, '1', ?, ?, NULL, ?, '百度影音', ?, NULL)",
                      moiveId, moiveInfo, script, url.getUrl());
                  dao.execute("COMMIT");
                }
                else
                {
                  dao.execute("INSERT INTO TB_SD_MOIVE_FILE VALUES (NULL, NOW(), NULL, '1', ?, ?, NULL, ?, '百度影音', ?, NULL)",
                      -1, moiveInfo, script, url.getUrl());
                  dao.execute("COMMIT");
                }
              }
              finally
              {
                dao.close(true);
              }
            }
            else if (isInfoPage)
            {
              /*
               * 电影介绍页面
               */
              if (nl.size() > 0)
              {
                Node ul = nl.elementAt(0).getChildren().elementAt(1);
                
                if (ul != null)
                {
//                  <ul>
//                  <li><h1>刺杀林肯</h1></li>
//                  <li>演员：<a href="/video/search/wd/%E6%AF%94%E5%B0%94%C2%B7%E5%9D%8E%E8%B4%9D%E5%B0%94/p/1.html" target="_blank">比尔·坎贝尔</a> <a href="/video/search/wd/%E6%9D%B0%E8%A5%BF%C2%B7%E7%BA%A6%E7%BF%B0%E6%A3%AE/p/1.html" target="_blank">杰西·约翰森</a> <a href="/video/search/wd/%E9%87%91%C2%B7%E8%BE%BE%E5%B8%83%E7%BD%97%E6%96%AF%E5%9F%BA/p/1.html" target="_blank">金·达布罗斯基</a> </li>
//                  <li>导演：<a href="/video/search/wd//p/1.html" target="_blank"></a> </li>
//                  <li>类型：<a href="/juqing/" target="_blank">剧情片</a></li>
//                  <li>地区：欧美</li>
//                  <li>上映：2013年</li>
//                  <li>状态：<span>完结</span></li>
//                  </ul>
                  String movieName = null;
                  List<String> actor = new ArrayList<String>();
                  String director = null;
                  String type = null;
                  String area = null;
                  String playYear = null;
                  for (Node li : ul.getChildren().toNodeArray())
                  {
                    if (li instanceof Tag)
                    {
                      Tag tag = (Tag) li;
                      
                      if (li.getFirstChild().getText().startsWith("演员："))
                      {
                        for (Node actorLink : li.getChildren().toNodeArray())
                        {
                          if (actorLink instanceof Tag)
                          {
                            try
                            {
                              actor.add(((Tag) actorLink).getFirstChild().getText());
                            }
                            catch (Exception e)
                            {
                              //actor.add("错误");
                            }
                          }
                        }
                      }
                      else if (li.getFirstChild().getText().startsWith("导演："))
                      {
                        try
                        {
                          director = (li.getChildren().elementAt(1).getFirstChild().getText());
                        }
                        catch (Exception e)
                        {
                          director = null;
                        }
                      }
                      else if (li.getFirstChild().getText().startsWith("类型："))
                      {
                        type = (li.getChildren().elementAt(1).getFirstChild().getText());
                      }
                      else if (li.getFirstChild().getText().startsWith("地区："))
                      {
                        area = (li.getFirstChild().getText().substring(3));
                      }
                      else if (li.getFirstChild().getText().startsWith("上映："))
                      {
                        playYear = (li.getFirstChild().getText().substring(3));
                      }
                      else if ("h1".equalsIgnoreCase(((Tag) tag.getChildren().elementAt(1)).getTagName()))
                      {
                        movieName = ((Tag) tag.getChildren().elementAt(1)).getFirstChild().getText();
                      }
                    }
                  }
                  
                  // 解析图片位置
                  parser.reset();
                  nl = parser.parse(new HasAttributeFilter("class", "o_big_img_bg_b"));
                  String imageUrl = null;
                  // <div class="o_big_img_bg_b"><img src="http://img.yetwo.com/uploads/video/2013-03-14/5141d1a18de85.jpg" title="" onerror="this.src='/views/images/nophoto.jpg'"/></div>
                  
                  if (nl.size() > 0)
                  {
                    imageUrl = ((Tag) nl.elementAt(0).getFirstChild()).getAttribute("src");
                  }
                  
                  // 解析电影内容
                  parser.reset();
                  nl = parser.parse(new HasAttributeFilter("class", "omov_list3"));
                  String moiveContent = null;
                  // <ul class="omov_list3"> <li>《杀死林
                  
                  if (nl.size() > 0)
                  {
                    moiveContent = nl.elementAt(0).getChildren().elementAt(1).toHtml();
                    //replaceAll("\\&[a-zA-Z]{1,10};", "").
                    moiveContent = moiveContent.replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
//                    System.out.println(moiveContent);
                  }
                  
                  DataAccessObject dao = StardustDB.getDataAccessObject();
                  
                  try
                  {
                    dao.execute("INSERT INTO TB_SD_MOIVE VALUES (NULL, NOW(), NULL, '1', ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0)",
                        movieName, YMXK_Main.toArrayString(actor), director, type, area, playYear, moiveContent, imageUrl, url.getUrl());
                    dao.execute("COMMIT");
                  }
                  finally
                  {
                    dao.close(true);
                  }
                }
              }
            }
          }
          catch (ParserException e)
          {
            e.printStackTrace();
          }
        }
      }
    }, 12);
    
    s.start();
    s.join();
  }

}
